<!DOCTYPE html>



  


<html class="theme-next gemini use-motion" lang="zh-Hans">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>
<meta name="theme-color" content="#222">






  
  
  <link rel="stylesheet" media="all" href="/lib/Han/dist/han.min.css?v=3.3">




<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />
















  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />







<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=5.1.4" rel="stylesheet" type="text/css" />


  <link rel="apple-touch-icon" sizes="180x180" href="/images/favicon.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon.png?v=5.1.4">


  <link rel="mask-icon" href="/images/favicon.png?v=5.1.4" color="#222">





  <meta name="keywords" content="APP开发," />





  <link rel="alternate" href="/atom.xml" title="平步青云win" type="application/atom+xml" />






<meta name="description" content="Java一般语法，以及在Android开发中的知识点和注意事项。">
<meta name="keywords" content="APP开发">
<meta property="og:type" content="article">
<meta property="og:title" content="Java面向对象编程">
<meta property="og:url" content="https://zxpgo.github.io/2018/10/31/Java面向对象编程/index.html">
<meta property="og:site_name" content="平步青云win">
<meta property="og:description" content="Java一般语法，以及在Android开发中的知识点和注意事项。">
<meta property="og:locale" content="zh-Hans">
<meta property="og:image" content="https://i.imgur.com/lDwfyRH.png">
<meta property="og:image" content="https://i.imgur.com/ZmeVedu.png">
<meta property="og:image" content="https://i.imgur.com/zUKDko6.png">
<meta property="og:image" content="https://i.imgur.com/QCEbhdB.png">
<meta property="og:image" content="https://i.imgur.com/6mbZzN8.png">
<meta property="og:image" content="https://i.imgur.com/OG3LyWU.png">
<meta property="og:image" content="https://i.imgur.com/oKFTJoU.png">
<meta property="og:image" content="https://i.imgur.com/qMFudIH.gif">
<meta property="og:image" content="https://i.imgur.com/q6Bnx3C.png">
<meta property="og:image" content="https://i.imgur.com/lAVMYxl.png">
<meta property="og:image" content="https://i.imgur.com/FWwFUDZ.png">
<meta property="og:image" content="https://i.imgur.com/ASMbTfu.png">
<meta property="og:updated_time" content="2018-11-07T13:19:16.815Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="Java面向对象编程">
<meta name="twitter:description" content="Java一般语法，以及在Android开发中的知识点和注意事项。">
<meta name="twitter:image" content="https://i.imgur.com/lDwfyRH.png">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Gemini',
    version: '5.1.4',
    sidebar: {"position":"right","display":"post","offset":10,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: 'PAO8LM7QB1',
      apiKey: '',
      indexName: 'Blog',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="https://zxpgo.github.io/2018/10/31/Java面向对象编程/"/>





  <title>Java面向对象编程 | 平步青云win</title>
  





  <script type="text/javascript">
    var _hmt = _hmt || [];
    (function() {
      var hm = document.createElement("script");
      hm.src = "https://hm.baidu.com/hm.js?7a4517a3ce6d7c50203655d056f01ac3";
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(hm, s);
    })();
  </script>




</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-right page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">平步青云win</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <h1 class="site-subtitle" itemprop="description"></h1>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/about/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-user"></i> <br />
            
            关于
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br />
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            归档
          </a>
        </li>
      
        
        <li class="menu-item menu-item-随笔">
          <a href="/sui" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-question-circle"></i> <br />
            
            随笔
          </a>
        </li>
      

      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
			
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br />
            
            搜索
          </a>
        </li>
      
    </ul>
  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off"
             placeholder="搜索..." spellcheck="false"
             type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="https://zxpgo.github.io/2018/10/31/Java面向对象编程/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="zxp">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/images/avatar.gif">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="平步青云win">
    </span>

    
      <header class="post-header">

        
        
          <h2 class="post-title" itemprop="name headline">Java面向对象编程</h2>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2018-10-31T21:40:14+08:00">
                2018-10-31
              </time>
            

            

            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/APP开发/" itemprop="url" rel="index">
                    <span itemprop="name">APP开发</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          
             <span id="/2018/10/31/Java面向对象编程/" class="leancloud_visitors" data-flag-title="Java面向对象编程">
               <span class="post-meta-divider">|</span>
               <span class="post-meta-item-icon">
                 <i class="fa fa-eye"></i>
               </span>
               
                 <span class="post-meta-item-text">阅读次数&#58;</span>
               
                 <span class="leancloud-visitors-count"></span>
             </span>
          

          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body han-init-context" itemprop="articleBody">

      
      

      
        <p>Java一般语法，以及在Android开发中的知识点和注意事项。<a id="more"></a></p>
<pre><code>private int calculatePrice(int quantity)
{}
</code></pre><p>private是访问修饰符，比如：public或private。这意味着calulatePrice方法只能被MainActivity里的其他方法调用，之外的部分无法调用它。如果声明位public，则所有代码都可以访问它。</p>
<p>int为返回类型。返回一个整型。</p>
<p>calculatePrice为函数名。</p>
<h2 id="资源"><a href="#资源" class="headerlink" title="资源"></a>资源</h2><p>资源放在文件<code>res</code>目录下，资源包括：图片、布局、</p>
<p>访问资源:</p>
<ul>
<li><p>在Java代码中： <code>R.类型名.资源名</code>，当编译项目时，Android中有一个AAPT的工具，会产生一个R类，（即一个叫R.java的文件）。</p>
</li>
<li><p>在XML代码中： <code>@类型名/资源名</code></p>
</li>
</ul>
<p><img src="https://i.imgur.com/lDwfyRH.png" alt=""></p>
<p>Java文件中有如下代码：</p>
<pre><code>setContentView(R.layout.activity_main);
</code></pre><p>该行代码表示我们引用了activity_main布局文件，展示了MainActivity怎么加载XML文件。</p>
<h2 id="对象"><a href="#对象" class="headerlink" title="对象"></a>对象</h2><p>XML中的视图，比如TextView、imageView实际上是通过应用里的Java对象控制的。</p>
<p>一个TextView对象有属性:</p>
<ul>
<li>字体大小</li>
<li>字体颜色</li>
<li>字体</li>
</ul>
<p>方法：</p>
<ul>
<li>setText()</li>
<li>getText()</li>
<li>setTextSize()</li>
<li>getTextSize()</li>
<li>onDraw()</li>
</ul>
<p>可以通过查看TextView.java文件，来指导TextView类有哪些属性和方法。</p>
<p>TextView类的简化版：</p>
<pre><code>/**
 * Displays text to the user.
 */
public class TextView extends View {

    // String value
    private String mText;

    // Text color of the text
    private int mTextColor;

    // Context of the app
    private Context mContext;

    /**
     * Constructs a new TextView with initial values for text and text color.
     */
    public TextView(Context context) {
      mText = &quot;&quot;;
      mTextColor = 0;
      mContext = context;
    }

    /**
     * Sets the string value in the TextView.
     *
     * @param text is the updated string to be displayed.
     */
    public void setText(String text) {
        mText = text;
    }

    /**
     * Sets the text color of the TextView.
     *
     * @param color of text to be displayed.
     */
    public void setTextColor(int color) {
        mTextColor = color;
    }

    /**
     * Gets the string value in the TextView.
     *
     * @return current text in the TextView.
     */
    public String getText() {
        return mText;
    }

    /**
     * Gets the text color of the TextView.
     *
     * @return current text color.
     */
    public int getTextColor() {
        return mTextColor;
    }
}
</code></pre><h3 id="创建对象"><a href="#创建对象" class="headerlink" title="创建对象"></a>创建对象</h3><p>通过调用构造函数来初始化一个对象</p>
<pre><code>TextView priceTextView = new TextView(content)
</code></pre><p>其中TextView(context)是调用构造函数，context是一个语境，可以帮助获取应用资源以及其他与语境有关的内容。</p>
<p>通过工厂方法来创建一个对象</p>
<pre><code>MediaPlayer player = MediaPlayer.create(context, R.raw.song);
</code></pre><p>其中create是MediaPlayer的工厂方法，得到一个名字为player的MediaPlayer对象。</p>
<p>构造函数创建对象使用较多，而工厂方法创建对象使用较少。至于使用哪一种方法，通过查看开发手册得知。</p>
<h3 id="对象调用方法"><a href="#对象调用方法" class="headerlink" title="对象调用方法"></a>对象调用方法</h3><p>调用格式：</p>
<pre><code>对象名.方法名(输入参数);

titleTextView.setText(&quot;News&quot;);
titleTextView.setTextSize(18);
titleTextView.setTextColor(Color.RED);
</code></pre><p>在类内部调用和类外部调用的区别：</p>
<p>类内部可以访问私有属性和私有方法，而外部只能访问类的公开方法和属性。另外，类内部访问不需要添加对象名，因为默认是this。而类外部访问需要添加对象名，如下：</p>
<p><img src="https://i.imgur.com/ZmeVedu.png" alt=""></p>
<h3 id="继承"><a href="#继承" class="headerlink" title="继承"></a>继承</h3><p>Java代码中，开始处有如下代码：</p>
<pre><code>public class MainActivity extends AppCompatActivity {

    int scoreTeamA = 0;
    int scoreTeamB = 0;
    @Override
}
</code></pre><p><code>extends AppCompatActivity</code>表明类<code>MainActivity</code>继承了<code>AppCompatActivity</code>的属性和方法。</p>
<p>如下方法，在MainActivity中没有定义，因此是继承自AppCompatActivity:</p>
<pre><code>setContentView(R.layout.activity_main);
TextView scoreView = (TextView) findViewById(R.id.team_b_score);
</code></pre><p>下面的代码，在方法声明前添加<code>@override</code>表明这是<strong>重载函数</strong>，即该函数在<code>AppCompatActivty</code>类中已经定义，但是在这里重新定义，做出一些修改。</p>
<pre><code>@Override
   protected void onCreate(Bundle savedInstanceState) {
       super.onCreate(savedInstanceState);
       setContentView(R.layout.activity_main);
   }
</code></pre><p>不同视图之间存在一些共性，比如，都具有大小、可以隐藏、位置等等。为了减少代码量，可以将这些相同的内容提出，放到一个新类View中，然后这些视图继承于View类。具体如下：</p>
<p><img src="https://i.imgur.com/zUKDko6.png" alt=""></p>
<p>这样，TextView类中只要编写与View类不同的部分，以及不希望继承View的内容重新编写即可。这样，TextView、ImageView、Button继承于View。</p>
<h3 id="通过资源编号获取视图对象"><a href="#通过资源编号获取视图对象" class="headerlink" title="通过资源编号获取视图对象"></a>通过资源编号获取视图对象</h3><pre><code>onCreate(R.layout.activity_main)
</code></pre><p>方法，是根据XML文件中的布局建立一个视图层次结构，如下：</p>
<p><img src="https://i.imgur.com/QCEbhdB.png" alt=""></p>
<p>具体原理如下：</p>
<p><img src="https://i.imgur.com/6mbZzN8.png" alt=""></p>
<pre><code>findViewByid(int id)
</code></pre><p>会找到传入的id相对应的View。findViewByid方法编程视图结构，找到视图层次结构中的某个View。该方法的返回值是View类型的对象。</p>
<p>findViewByid()方法返回的View类型，通常我们要使用具体的视图比如：TextView。因此需要进行强制转换：</p>
<pre><code>private void displayForTeamB(int score)
 {
     TextView scoreView = (TextView) findViewById(R.id.team_b_score);
     scoreView.setText(String.valueOf(score));
 }
</code></pre><p>其中<code>(TextView)</code>就是将View类型强制转换成TextView类型。如果不强制转换的话，无法调用<code>setText()</code>方法，因此View类型不具有该方法，只有TextView对象具有该方法。</p>
<h3 id="视图中读取数据"><a href="#视图中读取数据" class="headerlink" title="视图中读取数据"></a>视图中读取数据</h3><p><strong>Getter 和 Setter 方法概述</strong></p>
<p>已经使用过方法了，例如 setText 和 setImageResource。这些叫做 setter 方法，因为它们负责修改或操控视图的某个值（例如视图存储的文本或图片）。按照惯例，它们以“set”开头。</p>
<p>还有一种类别的方法，叫做<em>getter</em>方法，它们的唯一目的是从视图中“获取”值，例如获取视图的当前文本。按照惯例，它们以“get”开头。在下个练习中，我们将用到一些 getter 方法。</p>
<h3 id="日志"><a href="#日志" class="headerlink" title="日志"></a>日志</h3><p>先Android日志中写消息，在代码中写出如下类似的语句：</p>
<pre><code>Log.i(&quot;EnterpriseActivity.java&quot;, &quot;Captain&apos;s Log, Stardate 43125.8. We have entered a spectacular binary star system in the Kavis Alpha sector on a most critical mission of astrophysical research.&quot;);
</code></pre><p>第一个参数是日志语句来自的<strong>类的名称</strong>，第二个参数是想要显式地文字。</p>
<p>这里，我们使用了 Log.i()，表示“信息”级别的日志。其他级别的选项如下所示：</p>
<ul>
<li>e(String, String)（错误）</li>
<li>w(String, String)（警告）</li>
<li>i(String, String)（信息）</li>
<li>d(String, String)（调试）</li>
<li>v(String, String) (详情)</li>
</ul>
<p>读取TextView的内容，并输入到日志中：</p>
<pre><code>TextView textViewItem3 = (TextView) findViewById(R.id.menu_item_3);
String menuItem3 = textViewItem3.getText().toString();
Log.v(&quot;MainActivity&quot;, menuItem3);
</code></pre><p><img src="https://i.imgur.com/OG3LyWU.png" alt=""></p>
<h3 id="复选框"><a href="#复选框" class="headerlink" title="复选框"></a>复选框</h3><p>组件：</p>
<pre><code>&lt;CheckBox
    android:id=&quot;@+id/whipped_cream_checkbox&quot;    
    android:layout_width=&quot;wrap_content&quot;
    android:layout_height=&quot;wrap_content&quot;
    android:text=&quot;Whipped Cream&quot;
    android:layout_marginLeft=&quot;16dp&quot;
    android:paddingLeft=&quot;16dp&quot;
    android:textSize=&quot;26sp&quot;/&gt;
</code></pre><p>Java代码中获取CheckBox的状态，并在写入日志消息中：</p>
<pre><code>  CheckBox whippedCreamCheckBox = (CheckBox) findViewById(R.id.whipped_cream_checkbox);
boolean hasWhippedCream =  whippedCreamCheckBox.isChecked();
Log.v(&quot;MainActivity&quot;,&quot;The checkbox is &quot; + hasWhippedCream);
</code></pre><h3 id="布尔类型"><a href="#布尔类型" class="headerlink" title="布尔类型"></a>布尔类型</h3><p>声明：</p>
<pre><code>boolean hasWhippedCream = false;
</code></pre><p>变量名开头一般为“is”或“has”，这样，看变量名就知道该变量为布尔类型。</p>
<h3 id="滚动条"><a href="#滚动条" class="headerlink" title="滚动条"></a>滚动条</h3><p>在原来的代码的基础上，最外层套一个ScrollView视图即可，具体如下：</p>
<p>对于线性布局</p>
<pre><code>&lt;ScrollView
    xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;
    xmlns:tools=&quot;http://schemas.android.com/tools&quot;
    android:layout_width=&quot;match_parent&quot;
    android:layout_height=&quot;match_parent&quot;&gt;

    &lt;LinearLayout&gt;
        ...
    &lt;/LinearLayout&gt;

&lt;/ScrollView&gt;
</code></pre><p>对于相对布局</p>
<pre><code>&lt;ScrollView
    xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;
    xmlns:tools=&quot;http://schemas.android.com/tools&quot;
    android:layout_width=&quot;match_parent&quot;
    android:layout_height=&quot;match_parent&quot;&gt;

    &lt;RelativeLayout&gt;
        ...
    &lt;/RelativeLayout&gt;

&lt;/ScrollView&gt;
</code></pre><h3 id="输入框"><a href="#输入框" class="headerlink" title="输入框"></a>输入框</h3><p>XML中</p>
<pre><code>&lt;EditText
        android:id=&quot;@+id/name_edit_view&quot;
        android:layout_width=&quot;match_parent&quot;
        android:layout_height=&quot;wrap_content&quot;
        android:hint=&quot;Name&quot;
        android:inputType=&quot;textCapCharacters&quot;
        android:layout_marginTop=&quot;16dp&quot;/&gt;
</code></pre><p>Java代码中：</p>
<pre><code>EditText nameEditText = (EditText) findViewById(R.id.name_edit_view);
String name = nameEditText.getText().toString();
</code></pre><p>EditText继承于TextView，所以它具有getText方法。</p>
<p>在此，getText()返回类型为EditText，所以需要使用<code>.toString</code>将其转换为字符串类型。</p>
<h3 id="if-else"><a href="#if-else" class="headerlink" title="if/else"></a>if/else</h3><pre><code>if (numberOfGuests &lt; 6) {
     tip = 50;
} else if (numberOfGuests &lt; 20) {
     tip = 100;
} else {
     tip  = 1000;
}
</code></pre><h3 id="Toast"><a href="#Toast" class="headerlink" title="Toast"></a>Toast</h3><p>Toast用来在屏幕上显式消息。比如，如果预定的咖啡数量不能小于1，当数量等于之后，用户再点击减少时，在屏幕显示“预定咖啡数量不能小于1”。如下：</p>
<pre><code>if (quantity &lt; 1) 
{
    //通过toast,给出一个错误信息
    Toast.makeText(this, &quot;You cannot have less than 1 coffees.&quot;, Toast.LENGTH_LONG).show();
       //退出这个方法
    return;
}
</code></pre><p>创建Toast消息，需要调用Toast.makeText方法，并且输入三个参数，输入context指向这个activity。第二个参数是在屏幕上显示的消息内容。第三个参数指定它在屏幕显示的时间。最后这个对象调用show()方法来显示该消息。</p>
<h3 id="intent消息"><a href="#intent消息" class="headerlink" title="intent消息"></a>intent消息</h3><p>intent消息包含两个主要内容：</p>
<ul>
<li>动作</li>
<li>数据</li>
</ul>
<p>还可以指定额外消息：</p>
<ul>
<li>种类</li>
<li>成分</li>
<li>其他</li>
</ul>
<p>这些内容可以让Android决定哪个应用来处理该intent消息。</p>
<p>比如，电话intent消息：</p>
<pre><code>ACTIO_DAIL
tel:2125551212
</code></pre><p>注意数据格式采用：URI（uniform resource identifier），这是构建数据的标准方法。这样才可以正确处理该消息。</p>
<p>添加一个邮件intent:</p>
<pre><code>Intent intent = new Intent(Intent.ACTION_SENDTO);
intent.setData(Uri.parse(&quot;mailto:&quot;));//仅仅邮件APP处理该消息
intent.putExtra(Intent.EXTRA_SUBJECT, &quot;Just Java order for &quot; + name);//邮件标题
intent.putExtra(Intent.EXTRA_TEXT, priceMessage);//邮件内容
if (intent.resolveActivity(getPackageManager()) != null) //只有当APP接受了该消息，才开始启动
    startActivity(intent);
</code></pre><h3 id="本地化"><a href="#本地化" class="headerlink" title="本地化"></a>本地化</h3><p><code>res-&gt;values</code>该目录下是默认的语言文件。如果希望能根据系统语言来适配APP的语言，我们需要添加不同语言的资源文件。具体如下：</p>
<p><img src="https://i.imgur.com/oKFTJoU.png" alt=""></p>
<p>其中values-es表示西班牙语资源文件，values-fr表示法国语言资源文件。语言资源文件的格式如下：</p>
<pre><code>&lt;resources&gt;
    &lt;string name=&quot;app_name&quot;&gt;My Application&lt;/string&gt;
&lt;/resources&gt;
</code></pre><p>中间可以随机添加字符串。name表示该字符串的名字。在XML文件中，可以如下调用它：</p>
<pre><code>android:text = &quot;@string/name&quot;
</code></pre><p>在Java代码中，调用：</p>
<pre><code>getString(R.string.name);
</code></pre><p>这样，就不需要再XML和Java代码中出现字符串，字符串全部放在资源文件中。</p>
<p>在有些时候，可能不想翻译一部分文本字符串。例如，我们想要创建一个字符串，然后，留出一个空隙来添加变量。这个时候，需要使用<code>xliff</code>标签来标出不被翻译的部分。翻译用户的名字没有意义，但是翻译Name是有意义的。xliff标签给出一个名字的ID,在xliff标签中可以放入不用翻译的字符串，使用<code>%s</code>来代替，稍后会被id为name的字符串取代。具体如下：</p>
<pre><code>//resource
&lt;string name = &quot;order_summary_name&quot;&gt;Name: &lt;xliff:g id=&quot;name&quot; example&quot;Amy&quot;&gt;%s&lt;/xliff:g&gt;&lt;/string&gt;
//java
String priceMessage = getString(R.string.order_summary_anme, name);
</code></pre><p>以表格的形式查看<code>resource</code>文件中的语言种类：</p>
<p><img src="https://i.imgur.com/qMFudIH.gif" alt=""></p>
<h3 id="样式"><a href="#样式" class="headerlink" title="样式"></a>样式</h3><p>styles.xml文件中定义样式：</p>
<pre><code>&lt;!--style for a header TextView--&gt;
&lt;style name=&quot;CustomText&quot;&gt;
    &lt;item name=&quot;android:textSize&quot;&gt;26sp&lt;/item&gt;
    &lt;item name=&quot;android:textColor&quot;&gt;#4527A0&lt;/item&gt;
    &lt;item name=&quot;android:textStyle&quot;&gt;italic&lt;/item&gt;
&lt;/style&gt;
</code></pre><p>布局文件中调用styles.xml文件中的样式：</p>
<pre><code>&lt;TextView
       android:layout_width=&quot;wrap_content&quot;
       android:layout_height=&quot;wrap_content&quot;
       android:layout_margin=&quot;16dp&quot;
       android:text=&quot;TOPPINGS&quot;
       style=&quot;@style/CustomText&quot; /&gt;
</code></pre><p>调用的格式如：</p>
<pre><code>style=&quot;@style/样式名字&quot;
</code></pre><h3 id="主题"><a href="#主题" class="headerlink" title="主题"></a>主题</h3><p>styles.xml文件中最开始的代码：</p>
<pre><code>&lt;style name=&quot;AppTheme&quot; parent=&quot;Theme.AppCompat.Light.DarkActionBar&quot;&gt;
    &lt;!-- Customize your theme here. --&gt;
    &lt;item name=&quot;colorPrimary&quot;&gt;#009688&lt;/item&gt;
    &lt;item name=&quot;colorPrimaryDark&quot;&gt;#00796B&lt;/item&gt;
    &lt;item name=&quot;colorAccent&quot;&gt;#536DFE&lt;/item&gt;
&lt;/style&gt;
</code></pre><p>这是用来设置主题的风格，所有的视图都会使用该样式。可以改变应用栏或状态栏的颜色等特征。</p>
<p>样式被应用于一个单一的View，而主题被应用到活动或者应用中的所有View。</p>
<p>Android中有一些自带的标准系统主题。</p>
<p><img src="https://i.imgur.com/q6Bnx3C.png" alt=""></p>
<p>定义分别如下：</p>
<p><img src="https://i.imgur.com/lAVMYxl.png" alt=""></p>
<p>在此，使用上述第二种主题。在styles.xml文件中，使其称为父主题：</p>
   <style name="AppTheme" parent="android:Theme.Material.Light">
        <!-- Customize your theme here. -->
        <item name="android:colorPrimary">#80DEEA</item>
        <item name="android:colorPrimaryDark">#000000</item>
        <item name="android:colorAccent">#536DFE</item>
        <item name="android:windowBackground">#E0F7FA</item>
    </style>

<p>还可以在上述代码中，设置不同区域的颜色，这样会覆盖父主题的默认值。不同区域的名称：</p>
<p><img src="https://i.imgur.com/FWwFUDZ.png" alt=""></p>
<h3 id="应用清单"><a href="#应用清单" class="headerlink" title="应用清单"></a>应用清单</h3><p>每个应用的根目录中都必须包含一个<code>AndroidManifest.xml</code>文件（且文件名精确无误）。 清单文件向 Android 系统提供应用的必要信息，系统必须具有这些信息方可运行应用的任何代码。</p>
<pre><code> &lt;application
    android:allowBackup=&quot;true&quot;
    android:icon=&quot;@mipmap/ic_launcher&quot;
    android:label=&quot;@string/app_name&quot;
    android:roundIcon=&quot;@mipmap/ic_launcher_round&quot;
    android:supportsRtl=&quot;true&quot;
    android:theme=&quot;@style/AppTheme&quot;&gt;
    &lt;activity android:name=&quot;.MainActivity&quot;&gt;
        &lt;intent-filter&gt;
            &lt;action android:name=&quot;android.intent.action.MAIN&quot; /&gt;

            &lt;category android:name=&quot;android.intent.category.LAUNCHER&quot; /&gt;
        &lt;/intent-filter&gt;
    &lt;/activity&gt;
&lt;/application&gt;
</code></pre><p> <code>android:theme=&quot;@style/AppTheme&quot;</code>指出了所有活动都使用<code>AppTheme</code>主题，如果将该语句放到<code>MainActivity</code>活动中，这仅该活动使用<code>AppTheme</code>主题。由于上述代码中就一个活动，因此放在哪里都没关系。其中<code>AppTheme</code>主题风格在<code>styles.xml</code>文件的开头定义的。如下:</p>
<pre><code>&lt;application
    android:allowBackup=&quot;true&quot;
    android:icon=&quot;@mipmap/ic_launcher&quot;
    android:label=&quot;@string/app_name&quot;
    android:roundIcon=&quot;@mipmap/ic_launcher_round&quot;
    android:supportsRtl=&quot;true&quot;

    &lt;activity 
            android:name=&quot;.MainActivity&quot;
             android:theme=&quot;@style/AppTheme&quot;&gt;&gt;
        &lt;intent-filter&gt;
            &lt;action android:name=&quot;android.intent.action.MAIN&quot; /&gt;

            &lt;category android:name=&quot;android.intent.category.LAUNCHER&quot; /&gt;
        &lt;/intent-filter&gt;
    &lt;/activity&gt;
&lt;/application&gt;
</code></pre><h3 id="Android-找不到R类问题的解决方法"><a href="#Android-找不到R类问题的解决方法" class="headerlink" title="Android-找不到R类问题的解决方法"></a>Android-找不到R类问题的解决方法</h3><p><img src="https://i.imgur.com/ASMbTfu.png" alt=""></p>
<h4 id="重新检查资源文件中XML文件的有效性"><a href="#重新检查资源文件中XML文件的有效性" class="headerlink" title="重新检查资源文件中XML文件的有效性"></a>重新检查资源文件中XML文件的有效性</h4><p>如果最近一次编译时未生成R.java文件，则会引起项目资源引用错误，通常这是由于布局文件中的拼写错误导致的。因无法校验布局文件的有效性，IDE往往无法进行输入错误警示。改正错误并保存xml文件，IDE会重新生成R.java文件。</p>
<h4 id="删除gen目录"><a href="#删除gen目录" class="headerlink" title="删除gen目录"></a>删除gen目录</h4><p>若以上方法还不能够重新生成R.java文件，可以删除整个gen目录，IDE会重新生成R.java文件。</p>

      
    </div>
    
    
    

    
      <div>
        <div id="wechat_subscriber" style="display: block; padding: 10px 0; margin: 20px auto; width: 100%; text-align: center">
    <img id="wechat_subscriber_qcode" src="/images/wechat-qcode.jpg" alt="zxp wechat" style="width: 200px; max-width: 100%;"/>
    <div>欢迎关注微信公众号！</div>
</div>

      </div>
    

    
      <div>
        <div style="padding: 10px 0; margin: 20px auto; width: 90%; text-align: center;">
  <div></div>
  <button id="rewardButton" disable="enable" onclick="var qr = document.getElementById('QR'); if (qr.style.display === 'none') {qr.style.display='block';} else {qr.style.display='none'}">
    <span>打赏</span>
  </button>
  <div id="QR" style="display: none;">

    
      <div id="wechat" style="display: inline-block">
        <img id="wechat_qr" src="/images/WeChatpay.jpg" alt="zxp 微信支付"/>
        <p>微信支付</p>
      </div>
    

    
      <div id="alipay" style="display: inline-block">
        <img id="alipay_qr" src="/images/Alipay.jpg" alt="zxp 支付宝"/>
        <p>支付宝</p>
      </div>
    

    

  </div>
</div>

      </div>
    

    
      <div>
        <ul class="post-copyright">
  <li class="post-copyright-author">
    <strong>本文作者：</strong>
    zxp
  </li>
  <li class="post-copyright-link">
    <strong>本文链接：</strong>
    <a href="https://zxpgo.github.io/2018/10/31/Java面向对象编程/" title="Java面向对象编程">https://zxpgo.github.io/2018/10/31/Java面向对象编程/</a>
  </li>
  <li class="post-copyright-license">
    <strong>版权声明： </strong>
    本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/3.0/" rel="external nofollow" target="_blank">CC BY-NC-SA 3.0</a> 许可协议。转载请注明出处！
  </li>
</ul>

      </div>
    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tag/APP开发/" rel="tag"># APP开发</a>
          
        </div>
      

      
      
        <div class="post-widgets">
        

        

        
          
          <div id="needsharebutton-postbottom">
            <span class="btn">
              <i class="fa fa-share-alt" aria-hidden="true"></i>
            </span>
          </div>
        
        </div>
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2018/10/31/制作一款交互性应用/" rel="next" title="制作一款交互性应用">
                <i class="fa fa-chevron-left"></i> 制作一款交互性应用
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2018/11/01/利用Git提交代码至Github以及克隆/" rel="prev" title="利用Git提交代码至Github以及克隆">
                利用Git提交代码至Github以及克隆 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  
    <div class="comments" id="comments">
      <div id="lv-container" data-id="city" data-uid="MTAyMC8zODgxNC8xNTM0Mg=="></div>
    </div>

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image"
                src="/images/avatar.gif"
                alt="zxp" />
            
              <p class="site-author-name" itemprop="name">zxp</p>
              <p class="site-description motion-element" itemprop="description"></p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/archives/">
              
                  <span class="site-state-item-count">176</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                <a href="/categories/index.html">
                  <span class="site-state-item-count">16</span>
                  <span class="site-state-item-name">分类</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-tags">
                <a href="/tags/index.html">
                  <span class="site-state-item-count">48</span>
                  <span class="site-state-item-name">标签</span>
                </a>
              </div>
            

          </nav>

          
            <div class="feed-link motion-element">
              <a href="/atom.xml" rel="alternate">
                <i class="fa fa-rss"></i>
                RSS
              </a>
            </div>
          

          
            <div class="links-of-author motion-element">
                
                  <span class="links-of-author-item">
                    <a href="https://blog.csdn.net/qq_25774883" target="_blank" title="CSDN">
                      
                        <i class="fa fa-fw fa-globe"></i>CSDN</a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="https://github.com/zxpgo/zxpgo" target="_blank" title="GitHub">
                      
                        <i class="fa fa-fw fa-globe"></i>GitHub</a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="https://www.linkedin.com/feed/" target="_blank" title="LinkedIn">
                      
                        <i class="fa fa-fw fa-globe"></i>LinkedIn</a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="1165772354@qq.com" target="_blank" title="E-Mail">
                      
                        <i class="fa fa-fw fa-envelope"></i>E-Mail</a>
                  </span>
                
            </div>
          

          
          

          
          
            <div class="links-of-blogroll motion-element links-of-blogroll-inline">
              <div class="links-of-blogroll-title">
                <i class="fa  fa-fw fa-link"></i>
                友情链接
              </div>
              <ul class="links-of-blogroll-list">
                
                  <li class="links-of-blogroll-item">
                    <a href="http://theme-next.iissnan.com" title="Next主题" target="_blank">Next主题</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="http://blog.rexking6.top" title="青爷博客" target="_blank">青爷博客</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="https://me.csdn.net/download/qq_25774883" title="CSDN下载" target="_blank">CSDN下载</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="https://www.livere.com/" title="来必力" target="_blank">来必力</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="https://tongji.baidu.com/web/welcome/login" title="百度统计" target="_blank">百度统计</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="https://leancloud.cn/" title="LeanCloud" target="_blank">LeanCloud</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="http://ibruce.info/2015/04/04/busuanzi/" title="不蒜子" target="_blank">不蒜子</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="https://leetcode-cn.com/" title="LeetCode" target="_blank">LeetCode</a>
                  </li>
                
              </ul>
            </div>
          

          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#资源"><span class="nav-number">1.</span> <span class="nav-text">资源</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#对象"><span class="nav-number">2.</span> <span class="nav-text">对象</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#创建对象"><span class="nav-number">2.1.</span> <span class="nav-text">创建对象</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#对象调用方法"><span class="nav-number">2.2.</span> <span class="nav-text">对象调用方法</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#继承"><span class="nav-number">2.3.</span> <span class="nav-text">继承</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#通过资源编号获取视图对象"><span class="nav-number">2.4.</span> <span class="nav-text">通过资源编号获取视图对象</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#视图中读取数据"><span class="nav-number">2.5.</span> <span class="nav-text">视图中读取数据</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#日志"><span class="nav-number">2.6.</span> <span class="nav-text">日志</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#复选框"><span class="nav-number">2.7.</span> <span class="nav-text">复选框</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#布尔类型"><span class="nav-number">2.8.</span> <span class="nav-text">布尔类型</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#滚动条"><span class="nav-number">2.9.</span> <span class="nav-text">滚动条</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#输入框"><span class="nav-number">2.10.</span> <span class="nav-text">输入框</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#if-else"><span class="nav-number">2.11.</span> <span class="nav-text">if/else</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#Toast"><span class="nav-number">2.12.</span> <span class="nav-text">Toast</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#intent消息"><span class="nav-number">2.13.</span> <span class="nav-text">intent消息</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#本地化"><span class="nav-number">2.14.</span> <span class="nav-text">本地化</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#样式"><span class="nav-number">2.15.</span> <span class="nav-text">样式</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#主题"><span class="nav-number">2.16.</span> <span class="nav-text">主题</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#应用清单"><span class="nav-number">2.17.</span> <span class="nav-text">应用清单</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#Android-找不到R类问题的解决方法"><span class="nav-number">2.18.</span> <span class="nav-text">Android-找不到R类问题的解决方法</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#重新检查资源文件中XML文件的有效性"><span class="nav-number">2.18.1.</span> <span class="nav-text">重新检查资源文件中XML文件的有效性</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#删除gen目录"><span class="nav-number">2.18.2.</span> <span class="nav-text">删除gen目录</span></a></li></ol></li></ol></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div>
<script async src="https//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>
<i class="fa fa-user-md"></i><span id="busuanzi_container_site_pv" style='display:none'>
    本站总访问量 <span id="busuanzi_value_site_pv"></span> 
    <span class="post-meta-divider">|</span>
</span>
<span id="busuanzi_container_site_uv" style='display:none'>
    访问人数 <span id="busuanzi_value_site_uv"></span>
</span>
</div>


<script async src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>

<div class="copyright">&copy; 2018-8 &mdash; <span itemprop="copyrightYear">2020</span>
  <span class="with-love">
    <i class="fa fa-"></i> Power by 
  </span>
  <span class="author" itemprop="copyrightHolder">zxp</span>
  
  
</div>









        







        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    
      <div id="needsharebutton-float">
        <span class="btn">
          <i class="fa fa-share-alt" aria-hidden="true"></i>
        </span>
      </div>
    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  
    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.4"></script>



  
  


  <script type="text/javascript" src="/js/src/affix.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/schemes/pisces.js?v=5.1.4"></script>



  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  




  
  <div id="lv-container" data-uid="MTAyMC8zODgxNC8xNTM0Mg==">
    <script type="text/javascript">
      (function(d, s) {
        var j, e = d.getElementsByTagName(s)[0];
        if (typeof LivereTower === 'function') { return; }
        j = d.createElement(s);
        j.src = 'https://cdn-city.livere.com/js/embed.dist.js';
        j.async = true;
        e.parentNode.insertBefore(j, e);
      })(document, 'script');
    </script>
	</div>
  











  

  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url);
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  

  
  <script src="https://cdn1.lncld.net/static/js/av-core-mini-0.6.4.js"></script>
  <script>AV.initialize("2AyV3DKioBSdoryrFLRohzjB-gzGzoHsz", "XynedcHyJCVCrTfbD4yYnodo");</script>
  <script>
    function showTime(Counter) {
      var query = new AV.Query(Counter);
      var entries = [];
      var $visitors = $(".leancloud_visitors");

      $visitors.each(function () {
        entries.push( $(this).attr("id").trim() );
      });

      query.containedIn('url', entries);
      query.find()
        .done(function (results) {
          var COUNT_CONTAINER_REF = '.leancloud-visitors-count';

          if (results.length === 0) {
            $visitors.find(COUNT_CONTAINER_REF).text(0);
            return;
          }

          for (var i = 0; i < results.length; i++) {
            var item = results[i];
            var url = item.get('url');
            var time = item.get('time');
            var element = document.getElementById(url);

            $(element).find(COUNT_CONTAINER_REF).text(time);
          }
          for(var i = 0; i < entries.length; i++) {
            var url = entries[i];
            var element = document.getElementById(url);
            var countSpan = $(element).find(COUNT_CONTAINER_REF);
            if( countSpan.text() == '') {
              countSpan.text(0);
            }
          }
        })
        .fail(function (object, error) {
          console.log("Error: " + error.code + " " + error.message);
        });
    }

    function addCount(Counter) {
      var $visitors = $(".leancloud_visitors");
      var url = $visitors.attr('id').trim();
      var title = $visitors.attr('data-flag-title').trim();
      var query = new AV.Query(Counter);

      query.equalTo("url", url);
      query.find({
        success: function(results) {
          if (results.length > 0) {
            var counter = results[0];
            counter.fetchWhenSave(true);
            counter.increment("time");
            counter.save(null, {
              success: function(counter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(counter.get('time'));
              },
              error: function(counter, error) {
                console.log('Failed to save Visitor num, with error message: ' + error.message);
              }
            });
          } else {
            var newcounter = new Counter();
            /* Set ACL */
            var acl = new AV.ACL();
            acl.setPublicReadAccess(true);
            acl.setPublicWriteAccess(true);
            newcounter.setACL(acl);
            /* End Set ACL */
            newcounter.set("title", title);
            newcounter.set("url", url);
            newcounter.set("time", 1);
            newcounter.save(null, {
              success: function(newcounter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(newcounter.get('time'));
              },
              error: function(newcounter, error) {
                console.log('Failed to create');
              }
            });
          }
        },
        error: function(error) {
          console.log('Error:' + error.code + " " + error.message);
        }
      });
    }

    $(function() {
      var Counter = AV.Object.extend("Counter");
      if ($('.leancloud_visitors').length == 1) {
        addCount(Counter);
      } else if ($('.post-title-link').length > 1) {
        showTime(Counter);
      }
    });
  </script>



  

  
<script>
(function(){
    var bp = document.createElement('script');
    var curProtocol = window.location.protocol.split(':')[0];
    if (curProtocol === 'https') {
        bp.src = 'https://zz.bdstatic.com/linksubmit/push.js';        
    }
    else {
        bp.src = 'http://push.zhanzhang.baidu.com/push.js';
    }
    var s = document.getElementsByTagName("script")[0];
    s.parentNode.insertBefore(bp, s);
})();
</script>


  
  
  
  <link rel="stylesheet" href="/lib/needsharebutton/needsharebutton.css">

  
  
  <script src="/lib/needsharebutton/needsharebutton.js"></script>

  <script>
    
      pbOptions = {};
      
          pbOptions.iconStyle = "default";
      
          pbOptions.boxForm = "vertical";
      
          pbOptions.position = "top";
      
          pbOptions.networks = "Weibo,Wechat,Douban,QQZone,Twitter,Facebook";
      
      new needShareButton('#needsharebutton-postbottom', pbOptions);
    
    
      flOptions = {};
      
          flOptions.iconStyle = "box";
      
          flOptions.boxForm = "horizontal";
      
          flOptions.position = "middleRight";
      
          flOptions.networks = "Weibo,Wechat,Douban,QQZone,Twitter,Facebook";
      
      new needShareButton('#needsharebutton-float', flOptions);
    
  </script>

  

  
  


  
  <script type="text/javascript" src="/js/src/js.cookie.js?v=5.1.4"></script>
  <script type="text/javascript" src="/js/src/scroll-cookie.js?v=5.1.4"></script>


  
  <script type="text/javascript" src="/js/src/exturl.js?v=5.1.4"></script>


  
  
  	 <!-- custom analytics part create by xiamo -->
<script src="https://cdn1.lncld.net/static/js/av-core-mini-0.6.1.js"></script>
<script>AV.initialize("2AyV3DKioBSdoryrFLRohzjB-gzGzoHsz", "XynedcHyJCVCrTfbD4yYnodo");</script>
<script>
function showTime(Counter) {
	var query = new AV.Query(Counter);
	$(".leancloud_visitors").each(function() {
		var url = $(this).attr("id").trim();
		query.equalTo("url", url);
		query.find({
			success: function(results) {
				if (results.length == 0) {
					var content = $(document.getElementById(url)).text() + ' 0';
					$(document.getElementById(url)).text(content);
					return;
				}
				for (var i = 0; i < results.length; i++) {
					var object = results[i];
					var content = $(document.getElementById(url)).text() + ' ' + object.get('time');
					$(document.getElementById(url)).text(content);
				}
			}
		});

	});
}

</script>
  
</body>
</html>
